package cn.xuqiudong.admin.config;

import cn.xuqiudong.common.base.web.filter.BasicAuthorizationFilter;
import cn.xuqiudong.common.base.web.model.BasicToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2024-09-06 17:10
 */
@Configuration
public class AuthenticationConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationConfig.class);

    private Map<String, String> tokenMap;

    /**
     * 形如 user:passwd,user:passwd
     */
    @Value("${vic.basic.tokens}")
    public void setTokenMap(String tokenMapStr) {
        tokenMap = new HashMap<>();
        if (StringUtils.isNotBlank(tokenMapStr)) {
            String[] tokens = tokenMapStr.split(",");
            for (String token : tokens) {
                String[] userPass = token.split(":");
                tokenMap.put(userPass[0], userPass[1]);
            }
        }
        LOGGER.info("当前admin系统的合法用户为:{}", tokenMap);
    }



    @Bean
    public FilterRegistrationBean<BasicAuthorizationFilter> basicAuthorizationFilter() {
        FilterRegistrationBean<BasicAuthorizationFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new BasicAuthorizationFilter(validateToken()));
        registrationBean.setOrder(1);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }


    private Function<BasicToken, Boolean> validateToken() {
        return token -> tokenMap.containsKey(token.getSubject()) && StringUtils.equals(tokenMap.get(token.getSubject()), token.getCredential());
    }

    ;
}
